package cn.itcast.saveqq;

import android.content.Context;
import android.content.ContextWrapper;
import android.os.Environment;

import androidx.core.app.ActivityCompat;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class FileSaveQQ {
    public static boolean saveUserInfo(Context context, String account, String password){
        FileOutputStream fos = null;
        try{
            fos = context.openFileOutput("data.txt",Context.MODE_PRIVATE);
            fos.write((account + ":" + password).getBytes());
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }finally {
            try{
                if(fos != null){
                    fos.close();
                }
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static boolean saveUserInfoExt(Context context, String account, String password){
        String state = Environment.getExternalStorageState();
        if(state.equals(Environment.MEDIA_MOUNTED)){
            //File SDPath = Environment.getExternalStorageDirectory();
            ContextWrapper cw = new ContextWrapper(context);
            File SDPath = cw.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
            File file = new File(SDPath,"data.txt");
            String data = "Hello World!";
            FileOutputStream fos = null;
            try{
                fos = new FileOutputStream(file);
                fos.write(data.getBytes());
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                try{
                    if(fos != null){
                        fos.close();
                    }
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
        return true;
    }

    public static Map<String, String> getUserInfo(Context context){
        String content = "";
        FileInputStream fls = null;
        try{
            fls = context.openFileInput("data.txt");
            byte[] buffer = new byte[fls.available()];
            fls.read(buffer);
            content = new String(buffer);
            Map<String, String> userMap = new HashMap<String, String>();
            String[] infos = content.split(":");
            userMap.put("account", infos[0]);
            userMap.put("password",infos[1]);
            return userMap;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }finally {
            try{
                if(fls != null){
                    fls.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
